package com.logic.config.dao;

import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
    @Bean(name = "redisTemplate")
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // template.setEnableTransactionSupport(true); // 启用事务支持
        // 由于 Redis 事务的特性，你需要确保事务的提交是在所有操作完成后发生的。

        // 字符串序列化
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        // 非泛型序列化 Jackson2JsonRedisSerializer
        // 泛型序列化
        GenericJackson2JsonRedisSerializer genericJackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        //key序列化方式
        template.setKeySerializer(redisSerializer);
        template.setHashKeySerializer(redisSerializer);
        //value序列化
        template.setValueSerializer(genericJackson2JsonRedisSerializer);
        template.setHashValueSerializer(genericJackson2JsonRedisSerializer);

        return template;
    }

    @Bean(name = "valueOperations")
    public ValueOperations<Object, Object> valueOperations(RedisTemplate<Object, Object> hashOperations){
        return hashOperations.opsForValue();
    }

    @Bean(name = "hashOperations")
    public HashOperations<Object, Object, Object> hashOperations(RedisTemplate<Object, Object> hashOperations){
        return hashOperations.opsForHash();
    }
}
